package com.phiture.erp.produce.web.controller.admin;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
import com.phiture.erp.basic.api.pojo.resp.ErpMaterialInfoResp;
import com.phiture.erp.basic.api.pojo.resp.ErpMaterialResp;
import com.phiture.erp.basic.api.service.ErpMaterialApi;
import com.phiture.erp.produce.core.pojo.vo.ErpProduceRoutingDetailRespVO;
import com.phiture.erp.produce.core.pojo.vo.ErpProduceRoutingPageReqVO;
import com.phiture.erp.produce.core.pojo.vo.ErpProduceRoutingRespVO;
import com.phiture.erp.produce.core.pojo.vo.ErpProduceRoutingSaveReqVO;
import com.phiture.erp.produce.core.service.ErpProduceProcessService;
import com.phiture.erp.produce.core.service.ErpProduceRoutingService;
import com.phiture.erp.produce.dal.entity.ErpProduceProcessDO;
import com.phiture.erp.produce.dal.entity.ErpProduceRoutingDO;
import com.phiture.erp.produce.dal.entity.ErpProduceRoutingDetailDO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;


@Tag(name = "管理后台 - 工艺路线")
@RestController
@RequiredArgsConstructor
@RequestMapping("/erp/produce-routing")
@Validated
public class ErpProduceRoutingController {

    @Resource
    private ErpProduceRoutingService produceRoutingService;

    @Resource
    private ErpProduceProcessService erpProduceProcessService;

    private final ErpMaterialApi erpMaterialApi;

    private final DeptApi deptApi;

    @PostMapping("/create")
    @Operation(summary = "创建工艺路线")
    @PreAuthorize("@ss.hasPermission('erp:produce-routing:create')")
    public CommonResult<Long> createProduceRouting(@Valid @RequestBody ErpProduceRoutingSaveReqVO createReqVO) {
        return success(produceRoutingService.createProduceRouting(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新工艺路线")
    @PreAuthorize("@ss.hasPermission('erp:produce-routing:update')")
    public CommonResult<Boolean> updateProduceRouting(@Valid @RequestBody ErpProduceRoutingSaveReqVO updateReqVO) {
        produceRoutingService.updateProduceRouting(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除工艺路线")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:produce-routing:delete')")
    public CommonResult<Boolean> deleteProduceRouting(@RequestParam("id") Long id) {
        produceRoutingService.deleteProduceRouting(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得工艺路线")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:produce-routing:query')")
    public CommonResult<ErpProduceRoutingRespVO> getProduceRouting(@RequestParam("id") Long id) {
        ErpProduceRoutingDO produceRouting = produceRoutingService.getProduceRouting(id);
        return success(BeanUtils.toBean(produceRouting, ErpProduceRoutingRespVO.class, produceRoutingDetail -> {
            ErpMaterialResp material = erpMaterialApi.getMaterial(produceRouting.getMaterialId());
            produceRoutingDetail.setMaterialNumber(material.getBarCode());
            produceRoutingDetail.setMaterialName(material.getName());
        }));
    }

    @GetMapping("/page")
    @Operation(summary = "获得工艺路线分页")
    @PreAuthorize("@ss.hasPermission('erp:produce-routing:query')")
    public CommonResult<PageResult<ErpProduceRoutingRespVO>> getProduceRoutingPage(@Valid ErpProduceRoutingPageReqVO pageReqVO) {
        PageResult<ErpProduceRoutingDO> pageResult = produceRoutingService.getProduceRoutingPage(pageReqVO);

        Map<Long, ErpMaterialInfoResp> materialMap = erpMaterialApi.getMaterialMap(
                convertSet(pageResult.getList(), ErpProduceRoutingDO::getMaterialId));
        return success(BeanUtils.toBean(pageResult, ErpProduceRoutingRespVO.class, produceRouting ->{
            MapUtils.findAndThen(materialMap, produceRouting.getMaterialId(), material -> produceRouting.setMaterialNumber(material.getBarCode()));
            MapUtils.findAndThen(materialMap, produceRouting.getMaterialId(), material -> produceRouting.setMaterialName(material.getName()));
        }));
    }

    @GetMapping("/get/{materialId}")
    @Operation(summary = "获得工艺路线信息")
    @Parameter(name = "materialId", description = "物料ID")
    public CommonResult<Map<Long, String>> getProduceRoutingMap(@PathVariable("materialId") Long materialId) {
        Map<Long, String> produceRoutingMap = produceRoutingService.getProduceRoutingMap(materialId);
        return success(produceRoutingMap);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出工艺路线 Excel")
    @PreAuthorize("@ss.hasPermission('erp:produce-routing:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportProduceRoutingExcel(@Valid ErpProduceRoutingPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ErpProduceRoutingDO> list = produceRoutingService.getProduceRoutingPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "工艺路线.xls", "数据", ErpProduceRoutingRespVO.class,
                        BeanUtils.toBean(list, ErpProduceRoutingRespVO.class));
    }

    // ==================== 子表（工艺路线明细） ====================

    @GetMapping("/produce-routing-detail/list-by-routing-id")
    @Operation(summary = "获得工艺路线明细列表")
    @Parameter(name = "routingId", description = "工艺路线ID")
    @PreAuthorize("@ss.hasPermission('erp:produce-routing:query')")
    public CommonResult<List<ErpProduceRoutingDetailRespVO>> getProduceRoutingDetailListByRoutingId(@RequestParam("routingId") Long routingId) {
        List<ErpProduceRoutingDetailDO> result = produceRoutingService.getProduceRoutingDetailListByRoutingId(routingId);

        Map<Long, ErpProduceProcessDO> processMap = erpProduceProcessService.getProcessMap(
                convertSet(result, ErpProduceRoutingDetailDO::getProcessId));

        Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMap(
                convertSet(result, ErpProduceRoutingDetailDO::getWorkCenter));

        return success(BeanUtils.toBean(result, ErpProduceRoutingDetailRespVO.class, produceRoutingDetail -> {
            MapUtils.findAndThen(processMap, produceRoutingDetail.getProcessId(), process -> produceRoutingDetail.setProcessName(process.getProcessName()));
            MapUtils.findAndThen(processMap, produceRoutingDetail.getProcessId(), process -> produceRoutingDetail.setProcessCodeNo(process.getCodeNo()));
            MapUtils.findAndThen(deptMap, produceRoutingDetail.getWorkCenter(), dept -> produceRoutingDetail.setWorkCenterName(dept.getName()));
        }));
    }

    @GetMapping("/produce-routing-detail/list-by-material-id")
    @Operation(summary = "获得工艺路线明细列表")
    @Parameter(name = "materialId", description = "物料ID")
    public CommonResult<List<ErpProduceProcessDO>> getProduceRoutingDetailListByMaterialId(@RequestParam("materialId") Long materialId) {
        List<ErpProduceProcessDO> result = produceRoutingService.getProduceRoutingDetailListByMaterialId(materialId);
        return success(result);
    }

}